package com.hice.demo.sbdbra.common.util.email;

import com.hice.demo.sbdbra.common.util.ValidataUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.*;
import java.io.File;
import java.util.Date;
import java.util.Map;
import java.util.Properties;

public class SendMailUtils {
    private static Logger log = LoggerFactory.getLogger(SendMailUtils.class);
    public static String MAIL_SMTP_HOST = "mail.smtp.host";
    public static String MAIL_SMTP_PORT = "mail.smtp.port";
    public static String MAIL_SMTP_AUTH = "mail.smtp.auth";
    public static String MAIL_FROM_ACC = "mail.from.acc";
    public static String MAIL_FROM_PWD = "mail.from.pwd";
    public static String MAIL_FROM_NAME = "mail.from.name";
    public static String MAIL_TO_ACCS = "mail.to.accs";
    public static String MAIL_SUBJECT = "mail.subject";
    public static String MAIL_BODY = "mail.body";
    public static String MAIL_ATTACHMENT = "mail.attachment";

    public SendMailUtils() {
    }

    public static boolean sendTextMail(Map<String, ?> mailParams) throws Exception {
        return sendMail(mailParams, "text/html; charset=utf-8");
    }

    public static boolean sendHtmlMail(Map<String, ?> mailParams, File[] attachment) throws Exception {
        return sendMail(mailParams, "text/html; charset=utf-8");
    }

    private static boolean sendMail(Map<String, ?> mailParams, String type) throws Exception {
        if (!validataMailParams(mailParams)) {
            return false;
        } else {
            Properties props = new Properties();
            props.put(MAIL_SMTP_HOST, mailParams.get(MAIL_SMTP_HOST));
            props.put(MAIL_SMTP_PORT, mailParams.get(MAIL_SMTP_PORT));

            try {
                Session e2 = null;
                Object isAuth = mailParams.get(MAIL_SMTP_AUTH);
                if (isAuth != null && !StringUtils.equals((String) isAuth, "true")) {
                    props.put(MAIL_SMTP_AUTH, "false");
                    e2 = Session.getDefaultInstance(props, (Authenticator) null);
                } else {
                    props.put(MAIL_SMTP_AUTH, "true");
                    SmtpAuth msg = new SmtpAuth((String) mailParams.get(MAIL_FROM_ACC), (String) mailParams.get(MAIL_FROM_PWD));
                    e2 = Session.getDefaultInstance(props, msg);
                }

                MimeMessage var20 = new MimeMessage(e2);
                var20.setSentDate(new Date());
                InternetAddress fromAddress = new InternetAddress((String) mailParams.get(MAIL_FROM_ACC), mailParams.get(MAIL_FROM_NAME) == null ? null : (String) mailParams.get(MAIL_FROM_NAME), "UTF-8");
                var20.setFrom(fromAddress);
                String[] mailTos = ((String) mailParams.get(MAIL_TO_ACCS)).split(";");
                InternetAddress[] toAddress = new InternetAddress[mailTos.length];

                for (int mainPart = 0; mainPart < mailTos.length; ++mainPart) {
                    toAddress[mainPart] = new InternetAddress(mailTos[mainPart]);
                }

                var20.setRecipients(RecipientType.TO, toAddress);
                var20.setSubject(mailParams.get(MAIL_SUBJECT) == null ? null : (String) mailParams.get(MAIL_SUBJECT), "UTF-8");
                MimeMultipart var21 = new MimeMultipart();
                MimeBodyPart textBody = new MimeBodyPart();
                textBody.setContent((String) mailParams.get(MAIL_BODY), type);
                var21.addBodyPart(textBody);
                if (mailParams.get(MAIL_ATTACHMENT) != null) {
                    File[] transport = (File[]) ((File[]) mailParams.get(MAIL_ATTACHMENT));
                    File[] var12 = transport;
                    int var13 = transport.length;

                    for (int var14 = 0; var14 < var13; ++var14) {
                        File attachment = var12[var14];
                        MimeBodyPart attachmentBody = new MimeBodyPart();
                        FileDataSource source = new FileDataSource(attachment);
                        attachmentBody.setDataHandler(new DataHandler(source));
                        attachmentBody.setFileName(MimeUtility.encodeWord(attachment.getName()));
                        var21.addBodyPart(attachmentBody);
                    }
                }

                var20.setContent(var21);
                Transport var22 = e2.getTransport("smtp");
                var22.connect((String) mailParams.get(MAIL_SMTP_HOST), (String) mailParams.get(MAIL_FROM_ACC), (String) mailParams.get(MAIL_FROM_PWD));
                var20.saveChanges();
                var22.sendMessage(var20, var20.getAllRecipients());
                var22.close();
                return true;
            } catch (AuthenticationFailedException var18) {
                log.error("邮件身份验证失败", var18);
                throw var18;
            } catch (MessagingException var19) {
                log.error("邮件发送失败", var19);
                throw var19;
            }
        }
    }

    private static boolean validataMailParams(Map<String, ?> mailParams) throws IllegalArgumentException, ClassCastException {
        String mailSmtpHost = (String) mailParams.get(MAIL_SMTP_HOST);
        if (StringUtils.isEmpty(mailSmtpHost)) {
            throw new IllegalArgumentException("邮件服务器地址不可为空");
        } else {
            String mailSmtpPort = (String) mailParams.get(MAIL_SMTP_PORT);
            if (StringUtils.isEmpty(mailSmtpPort)) {
                throw new IllegalArgumentException("邮件服务器端口不可为空");
            } else if (NumberUtils.toInt(mailSmtpPort, -1) <= 0) {
                throw new IllegalArgumentException("邮件服务器端口参数错误");
            } else {
                String mailSmtpAuth = (String) mailParams.get(MAIL_SMTP_AUTH);
                if (StringUtils.isNotEmpty(mailSmtpAuth) && !StringUtils.equals(mailSmtpAuth, "true") && !StringUtils.equals(mailSmtpAuth, "false")) {
                    throw new IllegalArgumentException("邮件是否需要参数验证参数错误");
                } else {
                    String mailFromAcc = (String) mailParams.get(MAIL_FROM_ACC);
                    if (StringUtils.isEmpty(mailFromAcc)) {
                        throw new IllegalArgumentException("邮件发送账号不可为空");
                    } else if (!ValidataUtils.Email(mailFromAcc)) {
                        throw new IllegalArgumentException("邮件发送账号参数错误");
                    } else {
                        String mailFromPwd = (String) mailParams.get(MAIL_FROM_PWD);
                        if (StringUtils.isEmpty(mailFromPwd)) {
                            throw new IllegalArgumentException("邮件发送密码不可为空");
                        } else {
                            String mailToAccs = (String) mailParams.get(MAIL_TO_ACCS);
                            if (StringUtils.isEmpty(mailToAccs)) {
                                throw new IllegalArgumentException("邮件接受账户不可为空");
                            } else {
                                String[] mailToAcc = mailToAccs.split(";");
                                String[] mailBody = mailToAcc;
                                int var9 = mailToAcc.length;

                                for (int var10 = 0; var10 < var9; ++var10) {
                                    String acc = mailBody[var10];
                                    if (!ValidataUtils.Email(acc)) {
                                        throw new IllegalArgumentException("邮件接受账号参数错误");
                                    }
                                }

                                String var12 = (String) mailParams.get(MAIL_BODY);
                                if (StringUtils.isEmpty(var12)) {
                                    throw new IllegalArgumentException("邮件正文不可为空");
                                } else {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private static class SmtpAuth extends Authenticator {
        private String fromAcc;
        private String fromPwd;

        public SmtpAuth(String fromAcc, String fromPwd) {
            this.fromAcc = fromAcc;
            this.fromPwd = fromPwd;
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(this.fromAcc, this.fromPwd);
        }
    }
}
